package cn.signalpha.modules.shop.service;

import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.secure.utils.AuthUtil;
import cn.signalpha.core.tool.constant.SystemConstant;
import cn.signalpha.core.tool.node.ForestNodeMerger;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.shop.dto.StoreMenuDTO;
import cn.signalpha.modules.shop.entity.SellerMenu;
import cn.signalpha.modules.shop.entity.SellerRoleMenu;
import cn.signalpha.modules.shop.mapper.SellerMenuMapper;
import cn.signalpha.modules.shop.vo.SellerMenuVO;
import cn.signalpha.modules.shop.wrapper.SellerMenuWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static cn.signalpha.core.cache.constant.CacheConstant.MENU_CACHE;

/**
 * 服务类
 *
 * @author signalpha
 */
@Service
@AllArgsConstructor
public class SellerMenuService extends ServiceImpl<SellerMenuMapper, SellerMenu> {

	private final SellerRoleMenuService sellerRoleMenuService;
	private final static String PARENT_ID = "parentId";
	private final static Integer MENU_CATEGORY = 1;

	/**
	 * 懒加载列表
	 */
	public List<SellerMenuVO> lazyList(Long parentId, Map<String, Object> param) {
		if (Func.isEmpty(Func.toStr(param.get(PARENT_ID)))) {
			parentId = null;
		}
		return baseMapper.lazyList(parentId, param);
	}

	/**
	 * 懒加载菜单列表
	 */
	public List<SellerMenuVO> lazyMenuList(Long parentId, Map<String, Object> param) {
		if (Func.isEmpty(Func.toStr(param.get(PARENT_ID)))) {
			parentId = null;
		}
		return baseMapper.lazyMenuList(parentId, param);
	}

	/**
	 * 菜单树形结构
	 */
	public List<SellerMenuVO> routes(String roleId) {
		if (StringUtil.isBlank(roleId)) {
			return null;
		}
		List<SellerMenu> allSellerMenus = baseMapper.allMenu();
		List<SellerMenu> roleSellerMenus;
		// 超级管理员请求则返回全部菜单
		if (AuthUtil.isAdministrator()) {
			roleSellerMenus = allSellerMenus;
		}
		// 非超级管理员请求则返回对应角色权限菜单
		else {
			roleSellerMenus = baseMapper.roleMenuByRoleId(Func.toLongList(roleId));
		}
		return buildRoutes(allSellerMenus, roleSellerMenus);
	}

	/**
	 * 构建菜单树形结构
	 */
	private List<SellerMenuVO> buildRoutes(List<SellerMenu> allSellerMenus, List<SellerMenu> roleSellerMenus) {
		List<SellerMenu> routes = new LinkedList<>(roleSellerMenus);
		roleSellerMenus.forEach(roleMenu -> recursion(allSellerMenus, routes, roleMenu));
		routes.sort(Comparator.comparing(SellerMenu::getSort));
		SellerMenuWrapper sellerMenuWrapper = new SellerMenuWrapper();
		List<SellerMenu> collect = routes.stream().filter(x -> Func.equals(x.getCategory(), 1)).collect(Collectors.toList());
		return sellerMenuWrapper.listNodeVO(collect);
	}

	/**
	 * 递归处理权限
	 */
	private void recursion(List<SellerMenu> allSellerMenus, List<SellerMenu> routes, SellerMenu roleSellerMenu) {
		Optional<SellerMenu> menu = allSellerMenus.stream().filter(x -> Func.equals(x.getId(), roleSellerMenu.getParentId())).findFirst();
		if (menu.isPresent() && !routes.contains(menu.get())) {
			routes.add(menu.get());
			recursion(allSellerMenus, routes, menu.get());
		}
	}

	/**
	 * 按钮树形结构
	 */
	public List<SellerMenuVO> buttons(String roleId) {
		List<SellerMenu> buttons = (AuthUtil.isAdministrator()) ? baseMapper.allButtons() : baseMapper.buttons(Func.toLongList(roleId));
		SellerMenuWrapper sellerMenuWrapper = new SellerMenuWrapper();
		return sellerMenuWrapper.listNodeVO(buttons);
	}

	/**
	 * 树形结构
	 */
	public List<SellerMenuVO> tree() {
		return ForestNodeMerger.merge(baseMapper.tree());
	}

	/**
	 * 授权树形结构
	 */
	public List<SellerMenuVO> grantTree(TokenUser user) {
		return ForestNodeMerger.merge(AuthUtil.isAdministrator() ? baseMapper.grantTree() : baseMapper.grantTreeByRole(Func.toLongList(user.getRoleId())));
	}

	/**
	 * 角色所分配的树
	 */
	public List<String> roleTreeKeys(String roleIds) {
		List<SellerRoleMenu> roleMenus = sellerRoleMenuService.list(Wrappers.<SellerRoleMenu>query().lambda().in(SellerRoleMenu::getRoleId, Func.toLongList(roleIds)));
		return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
	}

	/**
	 * 获取配置的角色权限
	 */
	@Cacheable(cacheNames = MENU_CACHE, key = "'seller:auth:routes:' + #user.roleId")
	public List<Kv> authRoutes(TokenUser user) {
		List<StoreMenuDTO> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleId()));
		List<Kv> list = new ArrayList<>();
		routes.forEach(route -> list.add(Kv.create().set(route.getPath(), Kv.create().set("authority", Func.toStrArray(route.getAlias())))));
		return list;
	}

	/**
	 * 删除菜单
	 */
	public boolean removeMenu(String ids) {
		Long cnt = baseMapper.selectCount(Wrappers.<SellerMenu>query().lambda().in(SellerMenu::getParentId, Func.toLongList(ids)));
		if (cnt > 0) {
			throw new ServiceException("请先删除子节点!");
		}
		return removeByIds(Func.toLongList(ids));
	}

	/**
	 * 提交
	 */
	public boolean submit(SellerMenu sellerMenu) {
		LambdaQueryWrapper<SellerMenu> menuQueryWrapper = Wrappers.lambdaQuery();
		if (sellerMenu.getId() == null) {
			menuQueryWrapper.eq(SellerMenu::getCode, sellerMenu.getCode()).or(
				wrapper -> wrapper.eq(SellerMenu::getName, sellerMenu.getName()).eq(SellerMenu::getCategory, MENU_CATEGORY)
			);
		} else {
			menuQueryWrapper.ne(SellerMenu::getId, sellerMenu.getId()).and(
				wrapper -> wrapper.eq(SellerMenu::getCode, sellerMenu.getCode()).or(
					o -> o.eq(SellerMenu::getName, sellerMenu.getName()).eq(SellerMenu::getCategory, MENU_CATEGORY)
				)
			);
		}
		Long cnt = baseMapper.selectCount(menuQueryWrapper);
		if (cnt > 0) {
			throw new ServiceException("菜单名或编号已存在!");
		}
		if (sellerMenu.getParentId() == null && sellerMenu.getId() == null) {
			sellerMenu.setParentId(SystemConstant.TOP_PARENT_ID);
		}
		if (sellerMenu.getParentId() != null && sellerMenu.getId() == null) {
			SellerMenu parentSellerMenu = baseMapper.selectById(sellerMenu.getParentId());
			if (parentSellerMenu != null && parentSellerMenu.getCategory() != 1) {
				throw new ServiceException("父节点只可选择菜单类型!");
			}
		}
		sellerMenu.setIsDeleted(SystemConstant.DB_NOT_DELETED);
		return saveOrUpdate(sellerMenu);
	}

}

